// Copyright (c) [Year] [name of copyright holder]
// [Software Name] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2. 
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2 
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
// See the Mulan PSL v2 for more details.  
var ReResMap = [];
var typeMap = {
    "txt": "text/plain",
    "html": "text/html",
    "css": "text/css",
    "js": "text/javascript",
    "json": "text/json",
    "xml": "text/xml",
    "jpg": "image/jpeg",
    "gif": "image/gif",
    "png": "image/png",
    "webp": "image/webp"
}

function getLocalStorage() {
    ReResMap = window.localStorage.ReResMap ? JSON.parse(window.localStorage.ReResMap) : ReResMap;
}

function getLocalFileUrl(url) {
    var arr = url.split('.');
    var type = arr[arr.length - 1];
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, false);
    xhr.send(null);
    var content = xhr.responseText || xhr.responseXML;
    if (!content) {
        return false;
    }
    content = encodeURIComponent(
        type === 'js' ?
        content.replace(/[\u0080-\uffff]/g, function($0) {
            var str = $0.charCodeAt(0).toString(16);
            return "\\u" + '00000'.substr(0, 4 - str.length) + str;
        }) : content
    );
    return ("data:" + (typeMap[type] || typeMap.txt) + ";charset=utf-8," + content);
}
chrome.webRequest.onBeforeRequest.addListener(function(details) {
    var url = details.url;
    console.log('刷新页面:', url, ReResMap);
    var type = 1
    for (var i = 0, len = ReResMap.length; i < len; i++) {
        var reg = new RegExp(ReResMap[i].req, 'gi');
        console.log('监听:', ReResMap[i].checked, url.match(reg), typeof ReResMap[i].res === 'string');
        if (ReResMap[i].checked && typeof ReResMap[i].res === 'string' && reg.test(url)) {
            // console.log('判断:', ReResMap[i].checked, typeof ReResMap[i].res === 'string', reg.test(url));
            if (!/^file:\/\//.test(ReResMap[i].res)) {
                //                    return ReResMap[i].type === 'file' ?
                //                    {redirectUrl: ReResMap[i].res} :
                //                    {redirectUrl: url.replace(reg, ReResMap[i].res)};
                do {
                    type = 1
                    url = url.replace(reg, ReResMap[i].res);
                } while (reg.test(url))
            } else {
                // console.log('监听内容:', url.replace(reg, ReResMap[i].res));
                //                    return ReResMap[i].type === 'file' ?
                //                    {redirectUrl: getLocalFileUrl(ReResMap[i].res)} :
                //                    {redirectUrl: getLocalFileUrl(url.replace(reg, ReResMap[i].res))};
                do {
                    type = 2
                    console.log('获取监听内容:', ReResMap[i].res, ReResMap[i].req);
                    url = getLocalFileUrl(url.replace(reg, ReResMap[i].res));
                    console.log('url:', url);
                } while (reg.test(url))
            }
        }
    }
    if (type == 1) {
        console.log('返回修改1:', url);
    }
    if (type == 2) {
        console.log('返回修改2:', url);
    }
    // url == details.url ? {} : 
    return type == 2 ? { requestId: { redirectUrl: url } } : false;
}, { urls: ["<all_urls>"] }, ["blocking"]);

getLocalStorage();
console.log('背景页面');
window.addEventListener('storage', getLocalStorage, false);